# 在控制台输入起始页码，输入结束页码  然后把所有页数据下载到本地
# ajax 其实质是利用ajax对象(xmlHttpRequest xhr) 异步的向服务器发送请求， 服务器会返回部分数据
# 整个过程无刷新 不打断用户的操作
# https://movie.douban.com/j/chart/top_list?type=20&interval_id=100%3A90&action=&start=0&limit=20
# https://movie.douban.com/j/chart/top_list?type=20&interval_id=100%3A90&action=&start=20&limit=20
# https://movie.douban.com/j/chart/top_list?type=20&interval_id=100%3A90&action=&start=40&limit=20

# （1）request请求对象的定制
# （2）content获取响应源码
# （3）download
import urllib.request
import urllib.parse


def creat_request(page):
    url = 'https://movie.douban.com/j/chart/top_list?type=20&interval_id=100%3A90&action=&'
    # 1    0
    # 2    20
    # 3    40
    page = (page - 1) * 20
    data = {
        'start': page,
        'limit': 20
    }
    data = urllib.parse.urlencode(data)
    url = url + data
    headers = {

        'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50',
    }
    request = urllib.request.Request(url=url, headers=headers)
    return request


def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


def download(page, content):
    with open('moive_' + str(page) + '.json', 'w', encoding='utf-8') as fp:
        fp.write(content)


if __name__ == '__main__':
    start_page = int(input('请输入起始页码'))
    end_page = int(input('请输入结束页码'))

    for page in range(start_page, end_page + 1):
        # （1）request请求对象的定制
        request = creat_request(page)
        # （2）content获取响应源码
        content = get_content(request)
        # （3）download
        download(page, content)
    print('下载成功！！！')
